/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.consultorio.util;

import br.com.consultorio.bean.Pessoa;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author L3nfers
 */
@WebFilter(filterName = "filtraLogin", value = "/Consultorio/admin/")
public class FiltroUsuario implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Aqui Passou");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String cmd = request.getParameter("cmd");
        HttpServletRequest httpsr = (HttpServletRequest) request;
        System.out.println(httpsr.getServletPath());

        if (cmd == null) {
            cmd = "";
        }

        HttpSession session = ((HttpServletRequest) request).getSession(true);
        RequestDispatcher rd;
        Pessoa pessoa = (Pessoa) session.getAttribute("pessoa");

        if (httpsr.getServletPath().equals("/index.jsp")) {
            chain.doFilter(request, response);
        } else if (pessoa == null && cmd.equals("logar")) {
            chain.doFilter(request, response);
        } else if (pessoa != null) {
            chain.doFilter(request, response);
        } else {
            request.setAttribute("msg", "Você nao está logado no Sistema");
            rd = request.getRequestDispatcher("index.jsp");
            rd.forward(request, response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("Aqui Passou");
    }
}
